package com.webtest.filter;

import org.apache.commons.lang3.StringUtils;

import javax.servlet.*;
import java.io.IOException;

/**
 * @author lzy
 * @version v1.0
 * Create DateTime: 2018/8/15 12:49
 */
public class CheckNameFilter implements Filter {
    private String name;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        name = filterConfig.getInitParameter("name");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        String loginName = servletRequest.getParameter("name");
        StringBuilder builder = new StringBuilder();
        if (StringUtils.isEmpty(loginName)) {
            builder.append("登陆名称为空！").append("\n");
        }
        if (StringUtils.isEmpty(name)) {
            builder.append("无法读取到配置文件中的name属性！").append("\n");
        }
        if (!name.equals(loginName)) {
            builder.append("登陆名称错误！");
        }

        if (StringUtils.isEmpty(builder)) {
            filterChain.doFilter(servletRequest, servletResponse);
        } else {
            servletRequest.setAttribute("message", builder.toString());
            servletRequest.getRequestDispatcher("/filter/login.jsp").forward(servletRequest,servletResponse);
        }
    }

    @Override
    public void destroy() {

    }
}
